#region The MIT License
// The MIT License
// 
// Copyright (c) 2009 octalforty studios
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Data;
using System.IO;

using octalforty.Componento.ComponentModel.Impl;
using octalforty.Componento.ComponentModel.Installation;
using octalforty.Wizardby.Core.Db;

namespace octalforty.Componento.ComponentModel.Caching
{
    [Export(typeof(ICacheManagerService))]
    public class CacheManagerService : SQLiteServiceBase, ICacheManagerService
    {
        public CacheManagerService()
        {
            // TODO: Fix this. Static references to Directory should be replaced with calls to IFileSystemManagerService,
            // TODO: though then it will be neccessary to move database creation out of OnImportsSatisfied()
            DatabaseRootDirectory =
                Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                    @"octalforty\Componento");

            if(!Directory.Exists(DatabaseRootDirectory))
                Directory.CreateDirectory(DatabaseRootDirectory);
        }

        #region SQLiteServiceBase Members
        protected override string DatabaseFileName
        {
            get { return "componento.cache.db"; }
        }

        protected override string DatabaseMigrationDefinitionResourceName
        {
            get { return "octalforty.Componento.ComponentModel.Caching.Componento.Cache.mdl"; }
        }
        #endregion

        public void Add(string key, byte[] content)
        {
            DbUtil.ExecuteInTransaction(DbPlatform, ConnectionString,
                delegate(IDbTransaction transaction)
                    {
                        DbManager.Execute(DbPlatform.ProviderFactory, transaction,
                            "insert or replace into Cache (Key, UpdatedOn, Length, Content) values (:key, :updatedOn, :length, :content);",
                            new string[] { "key", "updatedOn", "length", "content" },
                            new object[] { key, DateTime.Now, content.GetLength(0), content });
                    });
        }

        public bool Exists(string key)
        {
            return DbUtil.ExecuteInTransaction<long>(DbPlatform, ConnectionString,
                delegate(IDbTransaction transaction)
                    {
                        return 
                            DbManager.ExecuteScalar<long>(DbPlatform.ProviderFactory, transaction,
                                "select count(*) > 0 from Cache where Key = :key",
                                new string[] { "key" },
                                new object[] { key  });
                    }) == 1;
        }

        public void Remove(string key)
        {
            DbUtil.ExecuteInTransaction(DbPlatform, ConnectionString,
                delegate(IDbTransaction transaction)
                    {
                        DbManager.Execute(DbPlatform.ProviderFactory, transaction,
                            "delete from Cache where Key = :key;",
                            new string[] { "key" },
                            new object[] { key });
                    });
        }

        public byte[] Get(string key)
        {
            List<byte[]> content = new List<byte[]>();

            DbUtil.ExecuteInTransaction(DbPlatform, ConnectionString,
                delegate(IDbTransaction transaction)
                    {
                        content.AddRange(
                            DbManager.ExecuteDataReader<byte[]>(DbPlatform.ProviderFactory, transaction,
                                "select Content from Cache where Key = :key",
                                new string[] { "key" },
                                new object[] { key  },
                                delegate(IDataReader dr) { return (byte[])dr.GetValue(0); }));
                    });

            return content.Count == 0 ?
                null :
                content[0];
        }

        public CacheEntryInfo GetCacheEntryInfo(string key)
        {
            List<CacheEntryInfo> info = new List<CacheEntryInfo>();

            DbUtil.ExecuteInTransaction(DbPlatform, ConnectionString,
                delegate(IDbTransaction transaction)
                    {
                        info.AddRange(
                            DbManager.ExecuteDataReader<CacheEntryInfo>(DbPlatform.ProviderFactory, transaction,
                                "select UpdatedOn, Length, Content from Cache where Key = :key",
                                new string[] { "key" },
                                new object[] { key  },
                                delegate(IDataReader dr)
                                    {
                                        return new CacheEntryInfo(dr.GetDateTime(0), dr.GetInt32(1), (byte[])dr.GetValue(2));
                                    }));
                    });

            return info.Count == 0 ?
                null :
                info[0];
        }

    }
}